﻿/* Get the state of the scores current game. */
function parHistoryState(){
	var par=wave.getParticipants();
	var parHistory={};
	for (i=0; i<par.length;i++){
		tmpStr=par[i].getId()+"_score";
		parHistory[tmpStr]=parScoreState(tmpStr);
		tmpStr=par[i].getId()+"_rightGuess";
		parHistory[tmpStr]=parScoreState(tmpStr);
		tmpStr=par[i].getId()+"_wrongeGuess";
		parHistory[tmpStr]=parScoreState(tmpStr);
		tmpStr=par[i].getId()+"_place";
		parHistory[tmpStr]=parScoreState(tmpStr);
	}
	return parHistory;
}

/* Get the participante's data from the state */
function parScoreState(str){
	return getSomething (str,[0]);
}

/* Get the current results column from the state as an array*/
/* (type==0) -> games results , (type==1) -> first prizes */
/*	if results are not present return []*/
function Results(type,ResultsStr){ 
	if(!ResultsStr){
		return [];
	}
	else{
		var TypesArray = ResultsStr.split("#");
		var ResultsArray = TypesArray[type].split("$");
		return ResultsArray;
	}
}

//this function translates the TOTO's correct result to OUR col number. for example: 'x'-->1
function translateCol(col){
	if (col==1) return 2;				
	if (col=='X') return 1;
	if (col==2) return 0;
}

//this function returns with col which is the correct results this week (in OUR terms, not TOTO terms);
function getWinnerCol(row,gamesResults){
	var returnedValue= translateCol(gamesResults[row]);
	return returnedValue;
}

//this function translates the TOTO's correct result Array to OUR correct results Array. for example: 'x'-->1
function translatedResultsArray(gamesResults){
	var translatedResults=new array();
	for (row=0;i<16;i++)
	{
		translatedResults[row]=translateCol(gamesResults[row]);
	}
	return translatedResults;
}

//this function builds the an array, representing the comparison between the user form and actual results
function buildCorrectResultsDisplayArray(gamesResults,row,col,game,correctResults){
	if (!game[row][col]) {//square is unmarked,
		if(col==translateCol(gamesResults[row])){ //square is unmarked, but in reality it was the result;
			return 3;
		}
		else{//square is unmarked, and in reality it wasn't the result;
			return 0;
		}
	}
	else{//if you are here - the square is marked	
		if(col==translateCol(gamesResults[row])){
			return 1; //it means the guess is correct
		}
		else{
			return 2;//it means the square is marked and incorrect
		}
	}
}

//This function keeps the current data in the state as last week's data
//need to change the idiot,prize etc. to getters (we shouldn't access the state directly);
function lastWeek(){
	var str=GamesStrState();
	var game = gameState();
	var results=correctResultsDisplayState();
	var agg_cost=getAggCost()+getCost();
		
	var agg_prize=getAggPrize();
	tmp=wave.getState().get("prize", "0");
	
	var agg_prizeArr=tmp.split(',');
	var l=agg_prizeArr.length;
	for (i=0;i<l;i++)
		agg_prize=agg_prize+Math.pow(1000,i)*parseInt(agg_prizeArr[l-i-1]);
	
	wave.getState().submitDelta({ 	"lw_game"  : wave.util.printJson( game ), //last week's filled form
		"lw_correctResultsDisplay": wave.util.printJson(results), //oren's results array from last week
		"lw_GamesStr" : str, //the names of last week's games
		"lw_prize"  : wave.getState().get("prize"), //how much money did the gruop win 
		"lw_idiotID" : wave.getState().get("idiotID"), //the id of last week's idiot
		"lw_hotID" : wave.getState().get("hotID"),
		"lw_cost" : wave.getState().get("cost"),
		"agg_prize": agg_prize,
		"agg_cost": agg_cost.toFixed(2),
		"lw_numberOfCorrectGuesses" : wave.getState().get("numberOfCorrectGuesses")}); 
}

/*********** Personal Profile History page **************************/

/*	This function is called when the personal profile button is clicked it */
	function openPersonalProfile(){
		updateParticipantsList();
		displayUserHistory(wave.getViewer().getId());
	}
/*	This function builds the drop-down participant list of the personal profile screen	*/	
	function updateParticipantsList(){
		var par=wave.getParticipants();
		document.getElementById("personal_profile_select").innerHTML = ""; // clearing
		Viewer = wave.getViewer();
		addItemToFormsTable(Viewer.getDisplayName(),Viewer.getId(),"personal_profile_select");//viewer first on list
		for (i =0 ; i<par.length ; i++){
			if(par[i]!=Viewer){
				addItemToFormsTable(par[i].getDisplayName(),par[i].getId(),"personal_profile_select");
			}
		}
	}

/*	Updating the display when picking a participant from the list. called on change of the drop-down list*/	
	function updateProfilePage(){
		parId = document.getElementById("personal_profile_select").value;
		displayUserHistory(parId);
	}
/*	This function calles the buildPerformanceTableAndGraph() function and enables visabilty of the data (when needed)*/	
	function displayUserHistory(parId){
		updatePersonalProfilePic(parId);
		if(getTBhistory(parId)==""){// no data on participant yet
			document.getElementById( "Personal_Profile_Area" ).setAttribute("style","display:none;");
			document.getElementById( "Summery_table_div" ).setAttribute("style","display:none;");
			document.getElementById("no_personal_profile").setAttribute("style","display:block;");
		}
		else{
			document.getElementById( "Personal_Profile_Area" ).setAttribute("style","display:block;");
			document.getElementById( "Summery_table_div" ).setAttribute("style","display:block;");
			document.getElementById("no_personal_profile").setAttribute("style","display:none;");
			buildPerformanceTableAndGraph(parId);
		}
		$.fn.colorbox.load();	
	}
	
	function updatePersonalProfilePic(parId){
		document.getElementById("personal_pic").innerHTML = "<img src="+wave.getParticipantById(parId).getThumbnailUrl()+" style='height:80px;width:80px'>";	
	}
	
/*	this is the main function of the personal profile feature. it builds the summerizing table and particiapant history graph*/	
	function buildPerformanceTableAndGraph(parId){
		// first obtaining participants data from the state
		userHesitationArray = getHasitaionhistory(parId).split("#");
		userTBArray = getTBhistory(parId).split("#");
		userDates = getUserDates(parId).split("#");
		TotalHesitation = sumArray(userHesitationArray);
		TotalTB = sumArray(userTBArray);
		userRightGuessArray = parScoreState(parId+'_rightGuess');
		userWrongGuessArray = parScoreState(parId+'_wrongeGuess');
		userPlacesArray = parScoreState(parId+'_place'); 
		// then build table
		document.getElementById("Summery_table_div").innerHTML = "<table cellpading='0' cellspacing='0' border='1' dir='rtl' class='summery_table'><tr><th>מדד</th><th>ציון כולל</th></tr>"+
                                "<tr><td>דירוג</td><td>"+(1/userPlacesArray[0])+"</td></tr>"+
                                "<tr><td>ניחושים נכונים</td><td>"+userRightGuessArray[0]+"</td></tr>"+
                                "<tr><td>טעויות</td><td>"+userWrongGuessArray[0]+"</td></tr>"+
								"<tr><td>אחוזי הצלחה</td><td>"+(Math.round(userRightGuessArray[0]*100/(Math.max(userWrongGuessArray[0]+userRightGuessArray[0],1))))+"%</td></tr>"+
                                "<tr><td>טוקבקים</td><td>"+TotalTB+"</td></tr>"+
                                "<tr><td>היסוסים</td><td>"+TotalHesitation+"</td></tr></table>";

		//finally build the graph with the google visualization API
		var data = new google.visualization.DataTable();
		data.addColumn('string', 'Date');
		data.addColumn('number', 'ביצועים ביחס לחברים');
		data.addColumn('number', 'ניחושים נכונים');
		data.addColumn('number', 'טעויות');
		data.addColumn('number', 'טוקבקים');
		data.addColumn('number', 'היסוסים');
		var n = userRightGuessArray.length;
		if (n<6){
			data.addRows(userRightGuessArray.length);
			data.setCell(0, 0, 'לא שיחקתי אז');
			data.setCell(0, 1, 0);
			data.setCell(0, 2, 0);
			data.setCell(0, 3, 0);
			data.setCell(0, 4, 0);
			data.setCell(0, 5, 0);
		}
		else{
			data.addRows(5);
			data.setCell(0, 0, Date2String(new Date(parseInt(userDates[n-6]))));
			data.setCell(0, 1, (userPlacesArray[n-5]*10));
			data.setCell(0, 2, userRightGuessArray[n-5]);
			data.setCell(0, 3, userWrongGuessArray[n-5]);
			data.setCell(0, 4, parseInt(userTBArray[n-6]));
			data.setCell(0, 5, parseInt(userHesitationArray[n-6]));
		}
		var dateCnt = 1;
		for(var t = ((n<6) ? 1 : n-4 ) ; t<n ; t++){
			data.setCell(dateCnt, 1, (userPlacesArray[t]*10));
			data.setCell(dateCnt, 2, userRightGuessArray[t]);
			data.setCell(dateCnt, 3, userWrongGuessArray[t]);
			data.setCell(dateCnt, 4, parseInt(userTBArray[t-1]));
			data.setCell(dateCnt, 5, parseInt(userHesitationArray[t-1]));
			data.setCell(dateCnt, 0, Date2String(new Date(parseInt(userDates[t-1]))));
			dateCnt++;
		}
		
				
/* 	Create and draw the visualization */
		var chart = new google.visualization.ImageLineChart(document.getElementById('line_div'));
		chart.draw(data, {width: 400,legend: 'top'});
	}
	
/*	Converting to a string minimized format*/
	function Date2String(D){
		str=D.getDate() + "/" + (D.getMonth()+1) + "/" + D.getFullYear();
		return str;
	}
/*	help function - returns the sum of an array */	
	function sumArray(Array){
		var sum = 0;
		for(var p = 0 ; p<Array.length ; p++){
			sum += parseInt(Array[p]);
		}
		return sum;	
	}
	
/********************************************************************NEW VERSION FOR PROFILES********************************************************************/
function uniqueArray(arr) {
	var a = [];
    var l = arr.length;
    for(var i=0; i<l; i++){
      for(var j=i+1; j<l; j++){
        if (arr[i] === arr[j])
          j = ++i;
      }
      a.push(arr[i]);
    }
    return a;
 }

 /*	This function is called when the results are at hand. 
	Calculations of achievements (groupwise and personal) are done. 
	Prize is calculted and other data is being processed*/
 function checkResults (ResultsStr){
	
	var correctResultsDisplayArray=defaultCorrectResultsDisplay();	//gets a default array, no guesses on the board
	var gamesResults=Results(0,ResultsStr); 						//returns an array of actual results from the state
	var gamesMoney=Results(1,ResultsStr); 							//returns an array of of prizes from the state
	var game = gameState();											//returns the toto form state
	var account=accountState(); 									//returns the account state, which says which user filled which square
	var correctResults=defaultCorrectResults();						//this array will hold, for each game, did we win or lose
	var winningSquare=new Array();									//this array will hold the winning squares for each game
	var par=wave.getParticipants();									//creates an array (par) of the wave's participants
	var counter=0;
	var parHistory=parHistoryState();
	var prize=0;											//init the prize won by the toto form
	var delta={};
	var scores=new Array();
	var totalScores=new Array();
	var sortedScores=new Array();
	var sortedTotalScores=new Array();
	var overArray=[1000000,200000,100000,50000,25000];
	function updateParHistory(value,type){
		if (type==0)
			str=parId+"_rightGuess";
		if (type==1)
			str=parId+"_wrongeGuess";
		if (type==2)
			str=parId+"_score";
		parHistory[str][0]=parHistory[str][0]+value;
		parHistory[str].push(value);
		delta[str]=wave.util.printJson(parHistory[str]);
	}
	//This function gets an array of participants (par) and returns an array 
	//with the hot's id in the first cell and the idiot's in the second
	function hotNot(scoresArray,sortedArray,flag){
		for ( i = 0; i < par.length; i++ ){
			var parId=par[i].getId();
			for ( j = 0; j < sortedArray.length; j++ ){
				if(scoresArray[parId]==sortedArray[j]){
					RS=(j+1)/sortedArray.length;
					if (flag)
						parHistory[parId+"_place"].push(RS);
					else
						parHistory[parId+"_place"][0]=RS;	
					if (RS==1)
						hot=parId;
					if ((RS==1/sortedArray.length)|(sortedArray.length==1))
						not=parId;
				}
			}
			delta[parId+"_place"]=wave.util.printJson(parHistory[parId+"_place"]);	 
		}
		if ((hot==not)&&(par.length>1))
			not=par[i-1].getId();
		
		if (flag){
			delta["hotID"]=hot;
			delta["idiotID"]=not;
		}
		else{
			delta["master_hotID"]=hot;
			delta["master_idiotID"]=not;
		}
	}
	gamesResults=reverseArray(gamesResults,16); 					//reverse the array we get from Results(1);
	for ( row = 0; row <16 ; row++ ){
		winningSquare[row]=getWinnerCol(row,gamesResults);			//finds the winning square for each of the games
	}	
	for ( row = 0; row <16 ; row++ ){
		if (game[row][winningSquare[row]]){  						//in case we guessed the result correctly
			counter++;												//updates the count of correct results
			correctResults[row]=1;									//update the correct results array with the correct guess.
		}
		for ( col = 0; col < 3; col++ ){
				correctResultsDisplayArray[row][col]=buildCorrectResultsDisplayArray(gamesResults,row,col,game,correctResults);
		}
	}
	//right guesses, wrong guesses, score - per participant
	for (iCR=0;iCR<par.length;iCR++){
		var rightGuess=0;
		var wrongeGuess=0;
		var normScore=0;
		var parId=par[iCR].getId();
		var par_profile=profileState(parId);
		for ( row = 0; row <16 ; row++ ){
			for ( col = 0; col < 3; col++ ){
				if (col==winningSquare[row]){
					if (par_profile[row][col]==1)
						rightGuess++;
				}
				else{
					if (par_profile[row][col]==1)
						wrongeGuess++;
				}
			}		
		}
		
		var par_score=rightGuess-wrongeGuess;
		updateParHistory(rightGuess,0);
		updateParHistory(wrongeGuess,1);
		updateParHistory(par_score,2);
		
		normScore=parHistory[parId+"_score"][0]/(parHistory[parId+"_score"].length-1);;
		totalScores[parId]=normScore;
		scores[parId]=par_score;
		sortedScores.push(par_score);
		sortedTotalScores.push(normScore);
		delta[parId+"_normScore"]=normScore;
		
	}
	
	sortedScores.sort(function(a,b){return a - b;});	//Sort numerically in descending order
	sortedTotalScores.sort(function(a,b){return a - b;});
	sortedScores=uniqueArray(sortedScores);
	sortedTotalScores=uniqueArray(sortedTotalScores);
	
	if (counter>11){ 
		if (gamesMoney[16-counter]=='עובר')
			prize=overArray[16-counter];
		else
			prize=gamesMoney[16-counter];
	}
	
	hotNot(scores,sortedScores,true);
	hotNot(totalScores,sortedTotalScores,false);
	
	delta["ResultsReq"]="1";	 //for display of results
	delta["correctResultsDisplay"]=wave.util.printJson( correctResultsDisplayArray );
	delta["numberOfCorrectGuesses"]=counter;
	delta["prize"]=prize;
	
	//TalkBacks and hasistations - per participant
	var tempTBhistory=0;
	var currentTBcount=0;
	var curDate = wave.getState().get("cellClickUpperLimit");
	for (iTB=0;iTB<par.length;iTB++){
		parId=par[iTB].getId();
		//Talkback count
		tempTBhistory= getTBhistory(parId);
		currentTBcount=getTBcounter(parId);
		tempTBhistory=( tempTBhistory=="" ? currentTBcount : (tempTBhistory + "#" + currentTBcount));
		delta[parId+"TBhistory"]=tempTBhistory;
		//hesitation count
		tempHhistory= getHasitaionhistory(parId);
		currentHcount=getSomething(parId+"HC",0);//hesitationcount
		tempHhistory=( tempHhistory=="" ? currentHcount : (tempHhistory + "#" + currentHcount));
		delta[parId+"Hasitaionhistory"]=tempHhistory;
		//list of dates where the participants played
		userDates = getUserDates(parId);
		userDates = ( userDates=="" ? curDate : (userDates + "#" + curDate));
		delta[parId+"UserDates"]=userDates;
	}
	
	wave.getState().submitDelta(delta);
}
/*	getter function for participant's dates when he played the game */	
	function getUserDates(parId){
		if ( wave.getState() ){
			var userDates = wave.getState().get(parId+"UserDates");
			return userDates ? userDates : "";
		}
		else
			return "";
	}
/*	getter function for the participant's TalkBack count history */	
	function getTBhistory(parId){
		if ( wave.getState() ){
			var TBhistory = wave.getState().get(parId+"TBhistory");
			return TBhistory ? TBhistory : "";
		}
		else
			return "";
	}
	
/*	getter function for participant's hesitations history */	
	function getHasitaionhistory(parId){
		if ( wave.getState() ){
			var Hasitaionhistory = wave.getState().get(parId+"Hasitaionhistory");
			return Hasitaionhistory ? Hasitaionhistory : "";
		}
		else
			return "";
	}
	